<template>
    <div class="industryLayout">
        <!-- 标题 -->
        <Title>
            <template #default>{{ title }}</template>
        </Title>
        <!-- 内容区 -->
        <section class="contentLayout" v-loading="loading">
            <!-- 表单设置 -->
            <div class="tableSet">
                <div>
                    <button class="addI0" @click="open('addFather')">
                        <div class="iconPlus">
                            <el-icon><Plus /></el-icon>
                        </div>
                        <div class="text">新建</div>
                    </button>
                </div>
                <div>
                    <el-tooltip content="刷新" placement="top">
                        <el-icon size="19" @click="Refresh">
                            <RefreshRight />
                        </el-icon>
                    </el-tooltip>
                </div>
                <div>
                    <el-tooltip content="密度" placement="top">
                        <el-dropdown
                            ref="dropdown1"
                            trigger="contextmenu"
                            @command="hCommand($event)"
                        >
                            <el-icon size="19" @click="GapSize">
                                <Sort />
                            </el-icon>
                            <template #dropdown>
                                <el-dropdown-menu>
                                    <el-dropdown-item command="default">
                                        {{ textSize[0] }}
                                    </el-dropdown-item>
                                    <el-dropdown-item command="midden">
                                        {{ textSize[1] }}
                                    </el-dropdown-item>
                                    <el-dropdown-item command="small">
                                        {{ textSize[2] }}
                                    </el-dropdown-item>
                                </el-dropdown-menu>
                            </template>
                        </el-dropdown>
                    </el-tooltip>
                </div>
                <div>
                    <el-tooltip content="列设置" placement="top">
                        <div>
                            <el-popover
                                placement="bottom-start"
                                :width="200"
                                trigger="click"
                            >
                                <template #reference>
                                    <el-icon size="19" @click="setHeader">
                                        <Setting />
                                    </el-icon>
                                </template>
                                <el-tree
                                    ref="treeRef"
                                    style="max-width: 600px"
                                    :data="headerList"
                                    show-checkbox
                                    node-key="id"
                                    default-expand-all
                                    :expand-on-click-node="false"
                                    check-on-click-node
                                    @check-change="nodeChange"
                                    :default-checked-keys="headerTableList"
                                    :props="{
                                        children: 'children',
                                        label: 'label',
                                    }"
                                />
                            </el-popover>
                        </div>
                    </el-tooltip>
                </div>
            </div>

            <!-- 表单内容 -->
            <div class="tabContent">
                <el-table
                    :data="tableData"
                    style="width: 100%"
                    :size="tableSize"
                    header-cell-class-name="btou"
                    table-layout="fixed"
                    row-key="id"
                >
                    <el-table-column
                        prop="index"
                        label="序号"
                        width="100"
                        v-if="headerTableList.indexOf(1) == -1 ? false : true"
                    />
                    <el-table-column
                        prop="name"
                        label="名称"
                        min-width="72"
                        v-if="headerTableList.indexOf(2) == -1 ? false : true"
                    />
                    <el-table-column
                        prop="updatedAt"
                        label="编辑时间"
                        min-width="142"
                        v-if="headerTableList.indexOf(10) == -1 ? false : true"
                    />
                    <el-table-column
                        label="操作"
                        min-width="108"
                        v-if="headerTableList.indexOf(11) == -1 ? false : true"
                    >
                        <template #default="scope">
                            <el-button
                                link
                                type="primary"
                                size="small"
                                class="del"
                                @click="open('addSon', scope.row)"
                                v-if="scope.row.level != 2"
                            >
                                新增子类
                            </el-button>
                            <el-button
                                link
                                type="primary"
                                size="small"
                                class="del"
                                @click="updateIndustryName(scope.row)"
                            >
                                编辑
                            </el-button>
                            <el-button
                                link
                                type="primary"
                                size="small"
                                class="del"
                                @click="deleteIndustryName(scope.row)"
                                v-if="!scope.row.children.length"
                            >
                                删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>

            <!-- 分页组件 -->
            <div class="example-pagination-block pageCom">
                <div class="example-demonstration">
                    第 {{ (currentPage - 1) * pageObj.per_page + 1 }}-{{
                        pageObj.total > currentPage * pageObj.per_page
                            ? currentPage * pageObj.per_page
                            : pageObj.total
                    }}
                    条/总共 {{ pageObj.total }} 条
                </div>
                <el-pagination
                    layout="prev, pager, next"
                    :total="pageObj.total"
                    :page-size="pageObj.per_page"
                    size="small"
                    :current-page="currentPage"
                    @current-change="currentChange"
                />
            </div>
        </section>
    </div>
</template>
    
<script setup>
import Title from "components/public/Title";
import { useRoute } from "vue-router";
import {
    getIndustryList,
    getAddIndustry,
    DeleteIndustry,
    UpdateIndustry,
} from "@/network/industry";
import { onMounted, ref } from "vue";

const route = useRoute();
const title = route.meta.title;

onMounted(() => {
    getIndustry();
});

const list = ref([]);
const tableData = ref([]);
const pageObj = ref({});

// 获取行业列表
const getIndustry = async () => {
    await getIndustryList(currentPage.value).then((res) => {
        // console.log(res);
        pageObj.value = res.data.meta;
        // console.log(pageObj.value);
        // 获取行业列表信息
        list.value = res.data.data.list;
        // 处理时间格式
        list.value.forEach((v) => {
            v.updatedAt = v.updatedAt.slice(0, 19).replace("T", " ");
        });
        // 对请求的值为null的属性赋值为 -
        list.value.forEach((v) => {
            v.birthday = v.birthday == null ? "-" : v.birthday;
            v.education = v.education == null ? "-" : v.education;
            v.experience = v.experience == null ? "-" : v.experience;
            v.gender = v.gender == null ? "-" : v.gender;
            v.jobStatus = v.jobStatus == null ? "-" : v.jobStatus;
            v.name = v.name == null ? "-" : v.name;
            v.salary = v.salary == null ? "-" : v.salary;
            v.skill = v.skill == null ? "-" : v.skill;
            v.updatedAt = v.updatedAt == null ? "-" : v.updatedAt;
        });
        // 将列表数据转换成树形数据
        let tempArr = ref([]);
        // 一级列表的内容提取
        tempArr.value = list.value.map((v) => {
            if (v.level == 0) {
                return {
                    id: v.id,
                    name: v.name,
                    updatedAt: v.updatedAt,
                    pid: v.pid,
                    level: v.level,
                    children: [],
                };
            }
        });
        // console.log(tempArr.value);
        // 将一级列表提取出来
        tableData.value = tempArr.value.filter((v) => v);
        // 给一级列表元素添加index
        tableData.value.forEach((v, i) => {
            v["index"] = i + 1;
        });
        // 将二级列表对应一级列表,根据一级的id 和 二级的pid相等的条件, 将二级列表插入到一级列表的children中
        list.value.map((v) => {
            if (v.level == 1) {
                for (var i = 0; i < tableData.value.length; i++) {
                    if (tableData.value[i].id == v.pid) {
                        tableData.value[i].children.push({
                            id: v.id,
                            name: v.name,
                            updatedAt: v.updatedAt,
                            pid: v.pid,
                            level: v.level,
                            children: [],
                        });
                        break;
                    }
                }
            }
        });
        // 给二级列表添加 index
        tableData.value.map((v) => {
            for (let i = 0; i < v.children.length; i++) {
                v.children[i]["index"] = i + 1;
            }
        });
        // 将三级列表对应二级列表,根据二级的id 和 三级的pid相等的条件, 将三级列表插入到二级列表的children中
        list.value.map((v) => {
            if (v.level == 2) {
                for (let i = 0; i < tableData.value.length; i++) {
                    for (
                        let j = 0;
                        j < tableData.value[i].children.length;
                        j++
                    ) {
                        if (tableData.value[i].children[j].id == v.pid) {
                            tableData.value[i].children[j].children.push({
                                id: v.id,
                                name: v.name,
                                updatedAt: v.updatedAt,
                                pid: v.pid,
                                level: v.level,
                                children: [],
                            });
                        }
                    }
                }
            }
        });
        // 给三级列表添加 index
        tableData.value.map((v) => {
            for (let i = 0; i < v.children.length; i++) {
                for (let j = 0; j < v.children[i].children.length; j++) {
                    v.children[i].children[j]["index"] = j + 1;
                }
            }
        });
    });

    // console.log(tableData.value);
    // console.log(list.value);
    loading.value = false;
};

// 刷新页面,并重新请求页面
const loading = ref(false); // 刷新
const Refresh = () => {
    // console.log("重新请求");
    loading.value = true;
    getIndustry();
};
// 改变表格大小
const dropdown1 = ref(); //显示尺寸按钮
const tableSize = ref("default"); //表格尺寸大小
const GapSize = () => {
    // console.log("间隔大小");
    // console.log(dropdown1.value);
    if (!dropdown1) return;
    dropdown1.value.handleOpen();
};
const textSize = ref(["默认", "中等 *", "紧凑"]);
function hCommand(e) {
    if (e == "default") {
        tableSize.value = "large";
        textSize.value = ["默认 *", "中等", "紧凑"];
    } else if (e == "midden") {
        tableSize.value = "default";
        textSize.value = ["默认", "中等 *", "紧凑"];
    } else if (e == "small") {
        tableSize.value = "small";
        textSize.value = ["默认", "中等", "紧凑 *"];
    } else {
        tableSize.value = "";
    }
}
// 表头中标签的展示和隐藏
const setHeader = () => {
    console.log("表头的展示与隐藏");
};
const treeRef = ref();
const headerTableList = ref([1, 2, 10, 11]);
const headerList = [
    {
        id: 0,
        label: "列设置", // `<button>重置</button>`
        children: [
            // { id: 20, label: "固定在左侧", children: [] },
            {
                id: 30,
                label: "不固定",
                children: [
                    {
                        id: 1,
                        label: "序号",
                    },
                    {
                        id: 2,
                        label: "名称",
                    },
                    {
                        id: 10,
                        label: "编辑时间",
                    },
                    {
                        id: 11,
                        label: "操作",
                    },
                ],
            },
            // {
            //     id: 40,
            //     label: "固定在右侧",
            //     children: [],
            // },
        ],
    },
];
// 当节点被点击的时候触发
const nodeChange = (obj) => {
    // console.log(treeRef.value.getCheckedKeys());
    headerTableList.value = treeRef.value.getCheckedKeys();
    // console.log("obj:  ");
    // console.log(obj);
    // console.log(treeRef.value.getNode(20));
    // removeNode();
    // if (obj.id > 0 && obj.id < 12) {
    //     treeRef.value.append(obj, 20);
    // }
};
// 新建行业名称
const open = (action, row) => {
    ElMessageBox.prompt("行业名称", "添加行业", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPattern: /([A-z]|[\u4e00-\u9fa5]){2,}/,
        inputErrorMessage: "请输入正确的行业名称",
        inputPlaceholder: "请输入行业名称",
        customClass: "addMessageBox",
    })
        .then(async ({ value }) => {
            if (value) {
                console.log(value);
                console.log(row);
                console.log(action);
                if (action == "addFather") {
                    await getAddIndustry({
                        //新增顶级父类
                        name: value,
                    });
                } else if (action == "addSon") {
                    // 新增子类
                    await getAddIndustry({
                        name: value,
                        pid: row.id,
                    });
                } else {
                    return;
                }
                Refresh();
            } else {
                return;
            }

            ElMessage({
                type: "success",
                message: `成功添加行业:${value}`,
            });
        })
        .catch(() => {
            ElMessage({
                type: "info",
                message: "取消操作",
            });
        });
};

// 编辑行业名称
const updateIndustryName = (row) => {
    console.log(row);
    ElMessageBox.prompt("行业名称", "编辑行业", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPattern: /([A-z]|[\u4e00-\u9fa5]){2,}/,
        inputErrorMessage: "请输入正确的行业名称",
        inputPlaceholder: "请输入行业名称",
        customClass: "addMessageBox",
        inputValue: row.name,
    })
        .then(async ({ value }) => {
            if (value) {
                console.log(value);
                console.log(row);
                if (row) {
                    // 编辑行业名称
                    await UpdateIndustry({
                        name: value,
                        id: row.id,
                    });
                } else {
                    return;
                }
                Refresh();
            } else {
                return;
            }

            ElMessage({
                type: "success",
                message: `成功添加行业:${value}`,
            });
        })
        .catch(() => {
            ElMessage({
                type: "info",
                message: "取消操作",
            });
        });
};

// 删除行业名称
const deleteIndustryName = (row) => {
    ElMessageBox.confirm('确定删除 "' + row.name + '" 吗?', "删除行业信息", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "deleteMessageBox",
    })
        .then(async () => {
            await DeleteIndustry(row.id);
            // await DeleteIndustry("RHE23V6U");
            Refresh();
            ElMessage({
                type: "success",
                message: "成功删除" + row.name,
            });
        })
        .catch(() => {
            ElMessage({
                type: "info",
                message: "取消操作",
            });
        });
};

// 分页组件
const currentPage = ref(1); // 当前页数
const currentChange = (page) => {
    currentPage.value = page;
    console.log(currentPage.value);
    Refresh();
};
</script>
    
<style lang="scss">
.industryLayout {
    .contentLayout {
        padding: 0 24px 16px;
        background: #fff;
        .tableSet {
            padding: 16px 0;
            display: flex;
            justify-content: flex-end;
            align-items: center;
            & > div {
                padding: 8px;
                .el-dropdown {
                    color: var(--color-text);
                }
                .addI0 {
                    padding: 6px 15px;
                    color: #fff;
                    background: var(--color-high-text);
                    border: 1px solid var(--color-high-text);
                    border-radius: 5%;
                    display: flex;
                    justify-content: space-between;
                    // align-items: center;
                    // line-height: 32px;
                    // height: 32px;
                    .iconPlus {
                        padding-top: 1px;
                    }
                    .text {
                        padding-left: 8px;
                    }
                }
            }
        }
        .tabContent {
            .btou {
                background: #fafafa !important;
                font-weight: 500;
                .cell {
                    border-left: 1px solid #0000000f;
                    color: var(--color-text);
                }
            }
            .cell {
                color: var(--color-text);
            }
            .del {
                color: #1890ff;
                font-size: 14px;
            }
            .el-table_1_column_1:not(.btou) {
                padding-left: 5px;
            }
        }
        .pageCom {
            display: flex;
            justify-content: flex-end;
            align-items: center;
            margin-top: 16px;
            li.is-active {
                border: 1px solid var(--color-high-text);
                font-weight: 500;
            }
            .number {
                font-size: 14px;
            }
        }
    }
}
// 消息弹出框
.el-overlay-message-box {
    top: -200px !important;

    .el-message-box.addMessageBox {
        --el-messagebox-width: 640px;
        height: 243px;
        padding: 0;
        // 头部标题
        .el-message-box__header {
            padding: 0 !important;
            border-bottom: 1px solid var(--border-color-tint);

            .el-message-box__title {
                padding: 16px 24px;
                font-size: 16px;
                color: var(--color-text) !important;
            }
            .el-message-box__headerbtn {
                width: 54px;
                height: 54px;
                .el-message-box__close {
                    font-size: 20px;
                }
            }
        }
        // 输入内容
        .el-message-box__content {
            padding: 24px;
            margin-bottom: 24px;
            .el-message-box__message {
                color: var(--color-text) !important;
            }
        }
        .el-message-box__btns {
            border-top: 1px solid var(--border-color-tint);
            padding: 10px 16px;
        }
    }
}
</style>